package com.leon.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        int size = byteBuf.readableBytes();
        byte[] bytes = new byte[size];
        byteBuf.readBytes(bytes);

        String s = new String(bytes);
        s = s.substring(s.indexOf("{"));

        Object deserialize = serializer.deserialize(clazz, s.getBytes());
        out.add(deserialize);
    }
}
